<?php

namespace app\data\command;

use app\data\service\AliService;
use think\admin\Command;
use think\admin\Exception;
use think\admin\Storage;
use think\console\Input;
use think\console\Output;
use think\facade\Log;

/**
 * 同步汽车
 * Class SyncCarInfo
 * @package app\data\command
 */
class SyncCarInfo extends Command
{
    protected function configure()
    {
        $this->setName('sync_car_info');
        $this->setDescription('同步汽车');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        while (true) {

            foreach ($this->app->db->name('car_infos')->where('is_sync', 0)->cursor() as $vo) try {

                $id = $vo['id'];

                $carInfo = $this->app->db->connect('car_review')->name('car_infos')->where('plate_number', $vo['plate_number'])->findOrEmpty();
                if (!$carInfo || empty($carInfo['phone'])) {
                    if ($vo['phone']) {
                        $user = $this->app->db->connect('car_review')->name('data_user')->where('phone', $vo['phone'])->findOrEmpty();
                        if ($user) {
                            $uuid = $user['id'];
                        }
                    }
                } else if (empty($carInfo['driving_image_1']) && empty($carInfo['driving_image_2'])) {
                    // 已经存在汽车了且无行驶证图片， 做覆盖处理
                    $update = $vo;
                    unset($update['id']);
                    unset($update['is_sync']);
                    unset($update['phone']);
                }

                if (!$carInfo) {
                    // 初次同步
                    if (!empty($uuid)) {
                        $vo['uuid'] = $uuid;
                    }
                    unset($vo['id']);
                    unset($vo['is_sync']);
                    $this->app->db->connect('car_review')->name('car_infos')->insert($vo);
                } else {

                    if (empty($carInfo['phone']) && $vo['phone']) {
                        // 二次同步，同步手机并匹配原有用户
                        $update['phone'] = $vo['phone'];
                        if (!empty($uuid)) {
                            $update['uuid'] = $uuid;
                        }
                    }

                    if (!empty($update)) {
                        $this->app->db->connect('car_review')->name('car_infos')->where('id', $carInfo['id'])->update($update);
                        unset($update);
                    }
                }

                $this->app->db->name('car_infos')->where('id', $id)->update(['is_sync' => 1]);

                $uuid = 0;

            }  catch (\Exception $exception) {
                Log::error('同步汽车-报错: ' . $exception->getMessage() . $exception->getFile() . ':' . $exception->getLine());
            }

            sleep(5);
        }
    }




}